<!--考证- 报考学员 -->
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>已报考学员-{{rowData.bkz_name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
<!--      <el-form-item label="学员姓名：">-->
<!--        <el-input size="small" style="width: 200px;" placeholder="请输入" />-->
<!--      </el-form-item>-->
      <el-form-item label="手机号：">
        <el-input size="small" style="width: 200px;" placeholder="请输入" />
      </el-form-item>
<!--      <span>学员姓名：<el-input size="small" style="width: 200px;" placeholder="请输入" /></span>-->
<!--      <el-form-item label="考评等级：">-->
<!--        <el-select size="small" v-model="formInline.parentcode" placeholder="请选择" @change="search">-->
<!--          <el-option label="全部" value="ALL"></el-option>-->
<!--          <el-option label="一级" value="FEIZHI"></el-option>-->
<!--          <el-option label="二级" value="JIUYI"></el-option>-->
<!--          <el-option label="三级" value="JINSHU"></el-option>-->
<!--          <el-option label="四级" value="SULIAO"></el-option>-->
<!--          <el-option label="五级" value="JIADIAN"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="参加培训：">-->
<!--        <el-select size="small" v-model="formInline.parentcode" placeholder="请选择" @change="search">-->
<!--          <el-option label="全部" value="ALL"></el-option>-->
<!--          <el-option label="是" value="TRAIN"></el-option>-->
<!--          <el-option label="否" value="UNTRAIN"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="已出成绩：">-->
<!--        <el-select size="small" v-model="formInline.parentcode" placeholder="请选择" @change="search">-->
<!--          <el-option label="全部" value="ALL"></el-option>-->
<!--          <el-option label="通过" value="PASS"></el-option>-->
<!--          <el-option label="不通过" value="UNPASS"></el-option>-->
<!--          <el-option label="未出成绩" value="NOTRETURN"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="已发证书：">-->
<!--        <el-select size="small" v-model="formInline.parentcode" placeholder="请选择" @change="search">-->
<!--          <el-option label="全部" value="ALL"></el-option>-->
<!--          <el-option label="已发放" value="YIFA"></el-option>-->
<!--          <el-option label="未发放" value="UNFA"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="报考类型：">-->
<!--        <el-select size="small" v-model="formInline.parentcode" placeholder="请选择" @change="search">-->
<!--          <el-option label="全部" value="ALL"></el-option>-->
<!--          <el-option label="团队报名" value="YIFA"></el-option>-->
<!--          <el-option label="个人报名" value="UNFA"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="">
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="clan">重置</el-button>
      </el-form-item>
      <el-form-item label="">
        <!--        <el-button size="small" type="primary" icon="el-icon-search" @click="search">批量分班</el-button>-->
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleExportPhone">导出手机号</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleExport">导出考生信息</el-button>
        <!--        <el-button size="small" type="primary" icon="el-icon-search" @click="clan">导出分班数据</el-button>-->
<!--        <el-button size="small" type="primary" icon="el-icon-search" @click="clan">导入成绩</el-button>-->
<!--        <el-button size="small" type="primary"  @click="handleEdit">导入证书发放</el-button>-->
      </el-form-item>
<!--      <div class="addBut">-->
<!--        <el-button  size="small" type="primary" icon="el-icon-add"  @click="itemAdd('add')">邀请参赛者完善资料</el-button>-->
<!--      </div>-->
    </el-form>
    <!--列表-->
    <el-table ref="multipleTable" size="small" @selection-change="selectChange" :data="itemList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" sortable prop="username" label="学员姓名" width="150">
      </el-table-column>
      <el-table-column align="center" sortable prop="phoneno" label="手机号" width="250">
      </el-table-column>
      <el-table-column align="center" sortable prop="bklx" label="报考类型" width="250">
      </el-table-column>
      <el-table-column align="center" sortable prop="kzl_levelname" label="考证等级" width="200">
      </el-table-column>
      <el-table-column align="center" sortable prop="ukz_jointrain" label="参加培训" width="200">
        <template v-slot="scope">
          {{ scope.row.ukz_jointrain === 1 ? '是' : '否'}}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="" label="福利开放" width="200">
        <template v-slot="scope">
          {{ openFl(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="kzinfo.bkz_bmenddate" label="福利有效期至" width="200">
      </el-table-column>
      <el-table-column align="center" sortable prop="kzinfo.bkz_kscj_desc" label="成绩" width="200">
      </el-table-column>
      <el-table-column align="center" sortable prop="cykzzs_fafangtype" label="证书" width="200">
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template v-slot="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">学员资料</el-button>
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">成绩</el-button>-->
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">证书发放</el-button>-->
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">导出资料包</el-button>-->
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">收件地址</el-button>-->
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">福利设置</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑子分类界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm">
        <el-form-item label="子类名称" prop="itemname">
          <el-input size="small" v-model="editForm.itemname" auto-complete="off" placeholder="请输入子分类名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="unitname">
          <el-input size="small" v-model="editForm.unitname" auto-complete="off" placeholder="请输入描述"  type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="itemprice">
          <el-input size="small" v-model="editForm.itemprice" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="itemunit">
          <el-input size="small" v-model="editForm.itemunit" placeholder="请输入单位"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 添加子分类界面 -->
    <el-dialog :title="title" :visible.sync="addFormVisible" width="50%" @click='closeDialog("add")'>
      <el-form label-width="80px" ref="editForm" :model="editForm">
        <el-form-item label="姓名" prop="itemname">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="unitname">
          <el-input size="small" v-model="editForm.phone" auto-complete="off" placeholder="请输入手机号" ></el-input>
        </el-form-item>
        <el-form-item label="分班" prop="itemprice">
          <el-select
            v-model="editForm.class"
            placeholder="请选择"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in fenban"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="参赛口号" prop="itemunit">
          <el-input size="small" v-model="editForm.kouhao" placeholder="请输入参赛口号"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="itemunit">
          <el-input size="small" v-model="editForm.content" placeholder="请输入个人简介"  type="textarea" ></el-input>
        </el-form-item>
        <el-form-item label="视频上传" prop="itemunit">
          <div class="upload-area">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-change="handleFileChange"
              :show-file-list="true"
              :file-list = "editForm.videolist"
              :auto-upload = "false"
              :limit ="1"
            >
              <el-button size="small" type="primary">上传课件视频</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="锁定" prop="itemunit">
          <el-checkbox v-model="editForm.unlock">锁定，参赛者不可修改信息</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("add")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import Pagination from '../../components/Pagination'
import { formatDate } from '../../utils/util'
import {
  createbjsuser,
  deletebjsuser,
  fileuploadres,
  querybjsuserlist,
  querykzbmusers, queryuserinfo,
  updatebjsuser
} from "../../api/InstitutionApi";
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: '添加分类',
      editFormVisible: false, //控制编辑页面显示与隐藏
      addFormVisible: false,  //控制添加页面显示与隐藏
      dataAccessshow: false, //控制数据权限显示与隐藏
      unitAccessshow: false, //控制所属单位隐藏与显示
      // 编辑与添加
      editForm: {
        name :'',  //姓名
        phone :'', ///手机号
        class :'', ///分班
        kouhao :'', ///口号
        content:'', ///个人简介
        videoCode: '', ///上传视频code
        videolist: [], ////上传视频
        unlock: false ////是否锁定
      },
      // 分班
      fenban: [
        { id: 1, name: '一班' },
        { id: 2, name: '二班' },
        { id: 3, name: '三班' },
        { id: 4, name: '四班' },
        { id: 4, name: '五班' },
      ],
      rowData: '',  ////考证数据
      // 请求分类明细数据参数
      formInline: {
        page: 1,
        limit: 10,
        deptId: '',
        userName: '',
        userMobile: '',
        parentcode: ''
      },
      // 删除子分类的id象
      deleteItemCode:{
        itemcode:''
      },
      // 分类明细数据
      itemList: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      isEdit: false,
    }
  },
  // 注册组件
  components: {
    Pagination
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.rowData = this.$route.query.rowData;
    console.log('item:', this.rowData);
    this.selectcanshiperson()
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 考证者
    selectcanshiperson() {
      querykzbmusers().then(res => {
        console.log('考证者:', res)
        if(res.data.base_info.length > 0) {
          this.itemList = res.data.base_info
          console.log('考证者-1:', this.itemList)
          this.itemList = this.itemList.map(item => ({
            ...item,
            username:'',
            phoneno: '',
            cykzzs_fafangtype: '未发放'
          }))
          this.selectUserInfo()
        }
      })
    },
    // 查询用户信息
    selectUserInfo() {
      for(let i=0; i<this.itemList.length; i++) {
        let usercode = this.itemList[i].user_code
        queryuserinfo({
          "usercode": usercode
        }).then(res => {
          console.log('userinfo:',res)
          let baseinfo = res.data.base_info
          if(baseinfo) {
            this.itemList[i].username = baseinfo.user_realname
            this.itemList[i].phoneno = baseinfo.user_phoneno
          }
        })
      }
      console.log('userinfo-1:',this.itemList)


    },
    // 开放福利
    openFl() {
      for(let i=0; i<this.itemList.length; i++) {
        let levelcode = this.itemList[i].kzl_code
        let openfuli = this.itemList[i].kzinfo.bkz_levels.filter(item => item.kzl_code == levelcode)
        let fulicontent = []
        fulicontent.push(openfuli[0].kcfl[0].flkcnames[0],openfuli[0].tkfl[0].fltknames[0])
        console.log('openfuli:',fulicontent)
        return fulicontent.join('、')
      }


    },
    // 获取数据方法
    getdata(parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      // 获取分类明细列表
      selectDetail(parameter).then(res => {
        this.loading = false
        // console.log('selectDetail',res)
        if (res.data.data.itemlist.length !== 0) {
          this.$message({
            type: 'info',
            message: res.data.msg
          })
          // 若是空的就给空的
          this.itemList = res.data.data.itemlist
        } else {
          this.itemList = res.data.data.itemlist
          // 分页赋值
          this.pageparm.currentPage = this.formInline.page
          this.pageparm.pageSize = this.formInline.limit
          this.pageparm.total = res.count
        }
      })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    //搜索事件
    search() {
      // console.log('item-formInline:',this.formInline.parentcode)
      this.getdata(this.formInline.parentcode)

    },
    clan() {

    },
    // 添加新课程
    itemAdd() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });
      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/onlineCourse/courseEdit',
        query: ''
      });
    },

    // 订单详情跳转
    orderDetails() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });
      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/pro/proDetails',
        query: ''
      });
    },

    // 跳转到新课程表
    courserTable() {
      this.$router.push({
        path: '/onlineCourse/courseTable',
        query: ''
      });
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      if (row !== undefined && row !== 'undefined') {
        this.addFormVisible = true
        this.isEdit = true
        this.title = '编辑参赛者'
        this.editForm.name = row.bjs_name
        this.editForm.phone = row.user_phoneno
        this.editForm.kouhao = row.user_cskh ///口号
        this.editForm.class = row.user_fenban
        this.editForm.content = row.user_desc
        this.editForm.videoCode = row.user_video_uri[0].imguri
        this.editForm.videolist.push({
          name:'XXXX.mp4',
          url: row.user_video_uri[0].url
        })
        this.editForm.unlock = row.user_islock === 1 ? true : false
        console.log('编辑参赛者:', this.editForm)
      } else {
        // console.log('add:',this.formInline.parentcode)
        this.addFormVisible = true
        this.isEdit = false
        this.title = '添加参赛者'
        this.editForm.name = ''
        this.editForm.phone = ''
        this.editForm.kouhao = ''
        this.editForm.class = ''
        this.editForm.content = ''
        this.editForm.videoCode = ''
        this.editForm.videolist=[]
        this.editForm.unlock = ''
      }
    },
    // 编辑提交方法
    submitForm(editData) {
      // console.log('editData',editData)
      this.$refs[editData].validate(valid => {
        if (valid) {
          // 请求方法，保存编辑的子分类
          saveClassify(this.editForm)
            .then(res => {
              this.editFormVisible = false
              this.loading = false

              if (res.data.iteminfo !== '') {
                // console.log('saveclass',this.formInline)
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '数据保存成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('保存失败，请稍后再试！')
            })
        } else {
          return false
        }
      })
    },

    // 视频上传
    handleFileChange(file, fileList){
      // 1.当文件变化时，需要首先将临时文件与文件名称存储入相应的数组对象中
      // 获取文件的临时路径（不同浏览器兼容处理）
      const tempPath = file.url || URL.createObjectURL(file.raw);
      // 调用存储函数
      // const newVideo = {
      //   name: file.name,
      //   url: tempPath
      // };
      // 将视频文件名字与临时路径进行存储
      this.editForm.videolist.push({
        name: file.name,
        url: tempPath
      })

      let formData = new FormData();
      // const fileupdown = this.fileList[0].raw; // 获取原始文件对象
      const fileupdown = file.raw
      // 文件形式上传
      formData.append('restype', '10'); // 资源类型：10=视频
      formData.append('resfile', fileupdown);
      console.log('当前文件列表:', formData);
      // 以文件形式上传视频到服务端
      this.fileuploadres(formData)
    },

    // 以文件形式上传视频
    fileuploadres(formData) {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '视频上传中 0%', // 初始文本
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      fileuploadres(formData,{
        headers:{
          'Content-Type': 'multipart/form-data' // 必须设置
        },
        onUploadProgress: (progressEvent) => {
          // 上传进度显示
          const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          loading.setText(`视频上传中 ${percent}%`);
        }
      }).then(res => {
        // 上传成功
        loading.close();
        this.$message.success('视频上传成功');
        console.log('video:',res )
        this.editForm.videoCode = res.data.res_code
      })
    },

    // 视频结束
    // 导出参赛者练习数据
    handleExport () {
      // 1. 把 Element-UI 表格转成二维数组,自动生成表格导出
      // const table = this.$refs.multipleTable.$el.querySelector('.el-table__body-wrapper table')
      // const wb = XLSX.utils.table_to_book(table, { raw: true })
      //
      // // 2. 生成 excel 二进制数据
      // const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      //
      // // 3. 保存文件
      // const blob = new Blob([wbout], { type: 'application/octet-stream' })
      // saveAs(blob, '分班表格.xlsx')
      //   ///////////////////////////////
      //自定义导出
      let nowDataTime = formatDate(new Date())
      console.log('日期时间:', nowDataTime)
      const header = ['参赛者姓名', '手机号', '分班', '人气排名' , '获得票数' , '题库练习次数', '题库练习时长(小时)', '模拟测试时长', '模拟测试时平均分' ]
      const body = this.itemList.map(r => [r.name, r.phone, r.class, r.votes, r.times])
      const ws = XLSX.utils.aoa_to_sheet([header, ...body])
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.jsrow.bjs_name+'竞赛_练习数据'+nowDataTime+'.xlsx')


    },

    // 导出手机号
    handleExportPhone() {
      //自定义导出
      let nowDataTime = formatDate(new Date())
      console.log('日期时间:', nowDataTime)
      const header = ['参赛者姓名', '手机号', '分班']
      const body = this.itemList.map(r => [r.name, r.phone, r.class, r.votes, r.times])
      const ws = XLSX.utils.aoa_to_sheet([header, ...body])
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.jsrow.bjs_name+'竞赛_练习数据'+nowDataTime+'.xlsx')

    },

    // 添加参赛者
    submitAddForm(){
      if(this.isEdit) {
        updatebjsuser({
        }).then(res => {
          console.log('isedit:',res)
        })
      } else {
        // 添加参赛者
        createbjsuser({
        }).then(res => {
          this.addFormVisible = false
          this.loading = false
          console.log('add参赛者：', res)
          this.selectcanshiperson()
          // if (res.data !== '') {
          //   this.getdata(this.formInline.parentcode)
          //   this.$message({
          //     type: 'success',
          //     message: '数据保存成功！'
          //   })
          // } else {
          //   this.$message({
          //     type: 'info',
          //     message: res.msg
          //   })
          // }
        })
          .catch(err => {
            this.addFormVisible = false
            this.loading = false
            this.$message.error('保存失败，请稍后再试！')
          })

      }
      // this.$refs[addData].validate(valid => {
      //   if (valid) {
      //
      //   } else {
      //     return false
      //   }
      // })
    },
    // // 选择复选框事件
    selectChange(val) {
      this.selectdata = val
    },
    // 关闭编辑、添加弹出框
    closeDialog(dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'perm') {
        this.dataAccessshow = false
      } else if (dialog === 'unit') {
        this.unitAccessshow = false
      } else if (dialog === 'add'){
        this.addFormVisible = false
      }
    },
    // 删除用户
    deleteUser(index, row) {
      this.deleteItemCode.itemcode = row.item_code
      this.$confirm('确认删减参赛者，参赛者已存数据将保留?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletebjsuser({
            "usercode" : row.user_code
          })
            .then(res => {
              console.log('删除', res)
              this.selectcanshiperson()
              // if (res.msg === '删除分类成功') {
              //   this.$message({
              //     type: 'success',
              //     message: '删除分类成功!'
              //   })
              //   this.getdata(this.formInline.parentcode)
              // } else {
              //   this.$message({
              //     type: 'info',
              //     message: res.msg
              //   })
              // }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.addBut {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.addBut-content {
  margin-right: 20px;
}
.userRole {
  width: 100%;
}
</style>



